# coding=utf-8
# encoding=utf-8
from sqlalchemy.ext.declarative import DeclarativeMeta
import json
import dateutil.parser
import decimal
from DataBase import Model
import DataBase.Model as Model
import datetime

CONVERTERS = {
    'datetime': dateutil.parser.parse,
    'decimal': decimal.Decimal,
}

def change2Jsonstr(Model):
    host = []
    host.append(Model)
    jsonstring = json.dumps(host, sort_keys=True, indent=4, cls=AlchemyEncoder, ensure_ascii=False)
    # jsonstring=demjson.encode(host,encoding='utf-8')
    return jsonstring

def change2ACStatus(JsonStr):
    model = json.loads(JsonStr, encoding='utf-8')
    return model.ACStatus().Json2ModelList(model)

class AlchemyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                try:
                    json.dumps(data)     # this will fail on non-encodable values, like other classes
                    fields[field] = data
                except TypeError:    # 添加了对datetime的处理
                    # if isinstance(data, datetime.datetime):
                    #     fields[field] = data.isoformat()
                    # elif isinstance(data, datetime.date):
                    #     fields[field] = data.isoformat()
                    # elif isinstance(data, datetime.timedelta):
                    #     fields[field] = (datetime.datetime.min + data).time().isoformat()
                    # else:
                    #     fields[field] = None
                    pass
            # a json-encodable dict
            return fields
        return json.JSONEncoder.default(self, obj)

class ResponseEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Model.Response):
            return{
                'meta':{
                    'success':obj.meta.success,
                    'message':obj.meta.message
                },
                'data':obj.data
            }
        return json.JSONEncoder.default(self, obj)